﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;

namespace blackhouse.Web.Google {
    public class AdWordsHelper {

        #region Properties

        private bool requestChecked;
        private bool cookieChecked;
        private bool isAdwordsUser;

        #endregion

        #region Constructors

        private AdWordsHelper() { 
        
        }

        #endregion

        #region Methods

        public static AdWordsHelper GetPageInstance() {
            AdWordsHelper helper = null;
            if (HttpContext.Current != null && HttpContext.Current.Handler != null) {
                Page page = HttpContext.Current.Handler as Page;
                if (page != null) {
                    if (!page.Items.Contains("Adwords")) {
                        helper = new AdWordsHelper();
                        page.Items.Add("Adwords", helper);
                    }
                    else
                        helper = page.Items["Adwords"] as AdWordsHelper;
                }
            }
            return helper;
        }

        public bool IsAdwordsUser() {
            this.CheckRequest();
            this.SetInstanceFromCookie();
            return this.isAdwordsUser;
        }

        public void SetInstanceFromCookie() {
            if (!this.cookieChecked && HttpContext.Current != null && HttpContext.Current.Request != null) {
                this.cookieChecked = true;
                HttpRequest request = HttpContext.Current.Request;
                HttpCookie adwordsUserCookie = request.Cookies["adwords_user"];
                this.isAdwordsUser = adwordsUserCookie != null && adwordsUserCookie.Value == "1";
            }
        }

        public void CheckRequest() {
            if (!this.requestChecked && HttpContext.Current != null && HttpContext.Current.Request != null) {
                this.requestChecked = true;
                if (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString["gclid"])) {
                    HttpContext.Current.Response.Cookies.Add(new HttpCookie("adwords_user", "1"));
                }
            }
        }

        #endregion

    }
}